<?php
/**
 * 用户个人中心页
 * Created by PhpStorm.
 * User: chen
 * Date: 2016/9/13
 * Time: 17:41
 */
namespace app\home\controller;
use app\common\controller\HomeBase;
use app\common\model\User as UserModel;
use app\common\model\Userinfo as UserinfoModel;
use think\Session;
use think\Request;
use Gregwar\Image\Image;//使用composer依赖的第三方扩展包 图像处理
class Userinfo extends HomeBase{
    //初始化
    public function _initialize()
    {
        parent::_initialize();
    }

    public function index () {
        $userinfo = new UserinfoModel;
        //批量赋值
        $this->assign([
            'userinfoData' => $userinfo->get_find_data(),
            'account' => UserModel::where(['id'=>Session::get('uid')])->value('account'),
        ]);
        return $this->fetch('index');
    }

    /**
     *  上传头像
     */
    public function uploadify_face() {
        $userinfo = new UserinfoModel;
        $request = Request::instance();
        //获取表单上传文件
        $file = $request->file('Filedata');
        // 上传文件验证
        // 验证条件
        $validate_img = [
            'ext'  => 'jpg,png,jpeg,gif',//允许上传的文件后缀 [数组|字符串]
            'size' => 3145728,//上传文件最大字节大小
//            'type' => '',//允许上传的文件类型 [数组|字符串]
        ];
        //保存文件名的规则 rule('md5') date，md5，sha1系统支持
        // 生成的目录结构
        // date : 20160923\f7bbac26c8593f0f55786a42b5a2cce1.jpg 同一天的图片会保存在同一目录中
        // md5 : 1c \ 1ad08c2aeb82af3129ad8904f17b7b.jpg  //随机生成目录 传一个文件会生成一个类型于"1c"这样的目录
        $info = $file->rule('date')->validate($validate_img)->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'face');
        if ($info) {
            // 获取上传后文件名  $info->getSaveName()
            $roorImg = '/uploads/face/' . $info->getSaveName();
            // 替换转义符重组新的全路径 $info->getSaveName() 获取的值为 20160923\f7bbac26c.jpg 需要替换转义字符
            $img = str_replace("\\","/",$roorImg);
            // 图片裁剪
//            $image = \think\Image::open("." . $img);
            $image = Image::open("." . $img);//composer第三方扩展包
            // 获取上传后文件目录
            $dir = explode("/",str_replace("\\","/",$info->getSaveName()));
            $data = [
                'face_50' => "." . '/uploads/face/' . $dir[0] . "/" . "mini_" . $dir[1],
                'face_80' => "." . '/uploads/face/' . $dir[0] . "/" . "middle_" . $dir[1],
                'face_180' => "." . '/uploads/face/' . $dir[0] . "/" . "max_" . $dir[1],
            ];
            // 按照原图的比例生成缩略图 居中生成
            /*$image->thumb(50,50,\think\Image::THUMB_CENTER)->save($data['face_50']);
            $image->thumb(80,80,\think\Image::THUMB_CENTER)->save($data['face_80']);
            $image->thumb(180,180,\think\Image::THUMB_CENTER)->save($data['face_180']);*/
            $image->forceResize(180,180)->save($data['face_180']);
            $image->forceResize(80,80)->save($data['face_80']);
            $image->forceResize(50,50)->save($data['face_50']);
            //删除旧图片
            $oldData = db('userinfo')->where(['uid' => Session::get('uid')])->field(['face50','face80','face180'])->find();
            if ($oldData['face50']) {
                unlink("." . $oldData['face50']);
                unlink("." . $oldData['face80']);
                unlink("." . $oldData['face180']);
            }
            //写入数据库
            $userinfo->isUpdate(true)->save([
                'face50' => '/uploads/face/' . $dir[0] . "/" . "mini_" . $dir[1],
                'face80' => '/uploads/face/' . $dir[0] . "/" . "middle_" . $dir[1],
                'face180' => '/uploads/face/' . $dir[0] . "/" . "max_" . $dir[1],
                'face' => $img
            ],['uid' => Session::get('uid')]);

            // 上传成功后 删除原图
//            unlink("." . $img);

            // 返回数据
            $face = '/uploads/face/' . $dir[0] . "/" . "max_" . $dir[1];
            return json(['status' => 1,'url' => $face]);

        } else {
            // 获取文件上传错误信息 $file->getError()
            return json(['status'=>0,'msg'=>$file->getError()]);
        }
    }

    /**
     * 修改用户的基本信息
     */
    public function edit_info() {
        $request = Request::instance();
        $userinfo = new UserinfoModel;
        if ($request->isAjax()) {
            if ($userinfo->send_userinfo()) {
                return ['status' => 1,'msg' => '保存成功.^_^'];
            } else {
                return ['status' => 0,'msg' => $this->userinfoModel->getError()];
            }
        }
    }


    /**
     * 修改密码
     */
    public function ajax_edit_pwd() {
        $request = Request::instance();
        $user = new UserModel();
        if ($request->isAjax()) {
            if ($user->send_editpwd()) {
                return ['status' => 1,'msg' => '修改密码成功.^_^'];
            } else {
                return ['status' => 0,'msg' => $user->getError()];
            }
        }
    }

    /**
     *  检测旧密码
     */
    public function ajax_check_pwd() {
        $request = Request::instance();
        $pwd = $request->post('oldpwd');
        $user = new UserModel();
        if ($request->isAjax()) {
            if ($user->check_pwd($pwd)) {
                return ['ok' => ''];
            } else {
                return ['error' => $user->getError()];
            }
        }
    }



    // 关联新增数据 测试关联 一对一
    // 操作User模型的 demo
    /*public function add()
    {
        $user           = new UserModel;
        $user->account     = 'thinkphp5';
        $user->password = '123456';
        $user->registime = time();
        if ($user->save()) {
            // 写入关联数据
            $profile['username'] = '刘晨';
            $profile['truename'] = '测试一下';
            $user->userinfo()->save($profile);
            return '用户[ ' . $user->account . ' ]新增成功';
        } else {
            return $user->getError();
        }
    }*/

    /**
     * 测试 更新
     */
    /*public function update($id)
    {

        //get($id) 返回当前模型的对象实例,可以直接使用方法,查询后,save()方法默认的是更新操作
        // $user->userinfo Userinfo模型对象实例
        // 如果不好区分更新还是新增可用isUpdate()来区分操作
        $user       = UserModel::get($id);
        $user->account = 'framework21';
        if ($user->isUpdate(true)->save()) {
            // 更新关联数据
            $user->userinfo->username = '测试更新数据';
            $user->userinfo->isUpdate(true)->save();
            return '用户[ ' . $user->account . ' ]更新成功';
        } else {
            return $user->getError();
        }
    }*/
}
